const express = require('express');
const { query } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取因子列表
router.get('/', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 20, search = '', category = '' } = req.query;
    const offset = (page - 1) * limit;

    let whereConditions = ['1=1'];
    let params = [];

    if (search) {
      whereConditions.push('(name LIKE ? OR description LIKE ?)');
      params.push(`%${search}%`, `%${search}%`);
    }

    if (category) {
      whereConditions.push('category = ?');
      params.push(category);
    }

    const whereClause = whereConditions.join(' AND ');

    const countResult = await query(
      `SELECT COUNT(*) as total FROM factors WHERE ${whereClause}`,
      params
    ) || [{ total: 0 }];

    const [{ total = 0 } = {}] = countResult;

    const factors = await query(
      `SELECT * FROM factors WHERE ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), offset]
    );

    res.json({
      data: factors,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: total,
        pages: Math.ceil(total / limit)
      }
    });

  } catch (error) {
    console.error('获取因子列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建衍生因子
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { name, description, formula, category, baseFactors } = req.body;
    const userId = req.user.id;

    const result = await query(
      'INSERT INTO factors (name, description, formula, category, type, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())',
      [name, description, formula, category, 'derived', userId]
    ) || { insertId: 0 };

    const factorId = result.insertId;

    // 保存基础因子关系
    if (baseFactors && baseFactors.length > 0) {
      for (const baseFactor of baseFactors) {
        await query(
          'INSERT INTO factor_relations (derived_factor_id, base_factor_id, weight) VALUES (?, ?, ?)',
          [factorId, baseFactor.id, baseFactor.weight]
        );
      }
    }

    res.status(201).json({
      message: '衍生因子创建成功',
      factorId
    });

  } catch (error) {
    console.error('创建衍生因子错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取因子树
router.get('/tree', authenticateToken, async (req, res) => {
  try {
    const categories = await query(
      'SELECT DISTINCT category FROM factors ORDER BY category'
    );

    const treeData = [];
    for (const cat of categories) {
      const factors = await query(
        'SELECT id, name, description, type FROM factors WHERE category = ? ORDER BY name',
        [cat.category]
      );

      treeData.push({
        title: cat.category,
        key: cat.category,
        children: factors.map(f => ({
          title: f.name,
          key: f.id,
          description: f.description,
          type: f.type
        }))
      });
    }

    res.json({ data: treeData });
  } catch (error) {
    console.error('获取因子树错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 查单条
router.get('/:id', async (req, res) => {
  try {
    const rows = await query('SELECT * FROM factors WHERE id = ?', [req.params.id]) || [];
    const [factor] = rows;
    if (!factor) return res.status(404).json({ message: '因子不存在' });
    res.json([factor]);
  } catch (error) {
    console.error('获取因子错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 查询总数
router.get('/', async (req, res) => {
  try {
    let countResult = await query('SELECT COUNT(*) as total FROM factors', [])
    if (!Array.isArray(countResult)) countResult = [{ total: 0 }];
    const [{ total = 0 } = {}] = countResult;
    res.json({ total });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 